<template>
  <div :key="Time" class="ServiceNotes" v-loading="loadPage">
    <template v-if="!loadPage">
      <template v-if="fields.length">
        <el-form
          v-show="isEditForm"
          class="advanced-search fwbz_edit"
          label-position="top"
          onsubmit="return false;"
        >
          <!-- 表单 -->
          <form-builder
            ref="form"
            v-show="Amendment"
            :value="formData"
            :fields="fields"
            @update="update"
            :form-status="formStatus"
            :formEditingMode="formEditingMode"
            @getDeleteFiles="getDeleteFiles"
          >
            <!-- 编号 -->
            <template slot="serviceNumber" slot-scope="{ field }">
              <form-item
                ref="serviceNumber"
                :label="field.displayName"
                style="width:100%;"
              >
                <!-- <form-text
                v-if="formData && !formData.serviceNumber"
                :field="field"
                :value="formData.serviceNumber"
                @update="update"
              /> -->
                <div class="form-item__text">
                  {{$t('im.detail.serviceNotes.tips1')}}
                </div>
              </form-item>
            </template>
            <!-- 咨询分类 -->
            <template slot="consultName" slot-scope="{ field }">
              <form-item
                ref="consultName"
                :label="field.displayName"
                style="width:100%;"
              >
                <form-cascader
                  :field="field"
                  :value="formData.consultName"
                  :tree="field.setting.dataSource"
                  @update="update"
                />
              </form-item>
            </template>
            <!-- 解决状态 -->
            <template slot="solveStatus" slot-scope="{ field, value }">
              <form-item
                ref="solveStatus"
                :label="field.displayName"
                style="width:100%;"
              >
                <form-select
                  :field="field"
                  :source="field.setting.dataSource"
                  :value="formData.solveStatus"
                  @update="update"
                />
              </form-item>
            </template>
            <!-- 服务备注 -->
            <template slot="serviceRemark" slot-scope="{ field }">
              <form-item
                ref="serviceRemark"
                :label="field.displayName"
                style="width:100%;"
                :isNotNull="true"
              >
                <!-- <form-textarea
                :field="field"
                :value="formData.serviceRemark"
                @update="update"
              /> -->
                <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="formData.serviceRemark" :at-users.sync="atUsers">
                  <template slot="item" slot-scope="item">
                    <img :src="head(item.user.head)">
                    <span>{{item.user.displayName}}</span>
                  </template>
                  <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="`${field.placeHolder}${$t('common.base.atSb')}`" maxlength="500" :rows="4"></textarea>
                </biz-at-textarea>
              </form-item>
            </template>
            <!-- 产品 -->
            <template slot="remarkProduct" slot-scope="{ field }">
              <form-item
                ref="remarkProduct"
                :label="field.displayName"
                style="width:100%;"
                :validation="validation.product"
              >
                <biz-remote-select
                  ref="product"
                  :field="field"
                  :is-show-select="true"
                  v-model="formData.remarkProduct"
                  :remote-method="searchProduct"
                  :placeholder="$t('task.tip.searchTip', {name: $t('common.base.product')})"
                  multiple
                  :computed-width-keys="['name', 'serialNumber']"
                  :keyword-length-limit="true"
                  cleared
                >
                  <div class="product-template-option" slot="option" slot-scope="{ option }">
                    <h3>{{ option.name }}</h3>
                    <p>
                      <span>
                        <label>{{$t('common.form.type.productNo')}}：</label>
                        <span>{{ option.serialNumber }}</span>
                      </span>
                      <span>
                        <label>{{$t('common.base.productType')}}：</label>
                        <span>{{ option.type }}</span>
                      </span>
                      <span>
                        <label>{{$t('common.base.customer')}}：</label>
                        <span>{{option.customer && option.customer.name}}</span>
                      </span>
                    </p>   
                  </div>
                </biz-remote-select>
              </form-item>
            </template>
          </form-builder>
          <!-- 数据展示 -->
          <div class="FormText" v-show="!Amendment">
            <form-view :fields="fieldsInfo" :value="Info">
              <!-- start 服务备注 -->
              <template slot="serviceRemark" slot-scope="{ field }">
                <div class="form-view-row">
                  <label>{{ field.displayName }}</label>
                  <!-- <div
                  class="form-view-row-content"
                  style="text-align: left;"
                  v-html="
                    Info.serviceRemark
                      ? Info.serviceRemark.replaceAll('/n', '<br />')
                      : ''
                  "
                ></div> -->
                  <biz-comment-html 
                    class="form-view-row-content" 
                    :html="Info.serviceRemark
                      ? Info.serviceRemark.replaceAll('/n', '<br />')
                    : ''">
                  </biz-comment-html>
                </div>
              </template>
              <!-- end 服务备注 -->
              <!-- start 产品 -->
              <template slot="remarkProduct" slot-scope="{ field }">
                <template v-if="Info.remarkProduct && Info.remarkProduct.length">
                  <div class="form-view-row" v-for="(product) in Info.remarkProduct" :key="product.id">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content">
                      <span class="link-text" @click="openProductView(product.id)">{{ product.name }}</span>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                  </div>
                </template>
              </template>
              <!-- end 产品 -->
              <!-- start 创建时间 -->
              <template slot="createTime" slot-scope="{ field }">
                <div class="form-view-row">
                  <label>{{ field.displayName }}</label>
                  <div class="form-view-row-content">
                    {{ Info.createTime | fmt_datetime}}
                  </div>
                </div>
              </template>
              <!-- end 创建时间 -->
              <!-- start 创建客服 -->
              <template slot="customerServiceName" slot-scope="{ field }">
                <div class="form-view-row">
                  <label>{{ field.displayName }}</label>
                  <div class="form-view-row-content">
                    {{ Info.customerServiceName }}
                  </div>
                </div>
              </template>
              <!-- end 创建客服 -->
              <!-- start 绑定账号 -->
              <template slot="createUserName" slot-scope="{ field }">
                <div class="form-view-row">
                  <label>{{ field.displayName }}</label>
                  <div class="form-view-row-content">
                    <span v-user="Info.relationUserid||Info.createUid" class="user-card-triggle">{{ Info.createUserName }}</span>
                  </div>
                </div>
              </template>
            <!-- end 绑定账号 -->
            </form-view>
          </div>
        </el-form>
        <template v-if="!Amendment && !Object.keys(Info).length">
          <no-data-view-new></no-data-view-new>
        </template>
        <!-- 未传入ID，不展示操作栏 -->
        <div v-if="id && isShowOperateRow" class="title">
          <template v-if="Amendment">
            <el-button @click="Edit(false)">{{$t('common.base.cancel')}}</el-button>
            <el-button
              type="primary"
              v-if="conversationStatus !== 3 && isConversation"
              @click="SaveEnd"
            >{{$t('common.base.saveAndToBeEnd')}}</el-button
            >
            <el-button
              type="primary"
              :loading="loading"
              @click="Save(false)">
              {{$t('common.base.save')}}
            </el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="Edit(true)">
              {{ Object.keys(Info).length ? $t('common.base.edit') : $t('common.base.addRemark') }}
            </el-button>
          </template>
        </div>
      </template>
      <template v-else>
          <no-data-view-new :notice-msg="$t('im.detail.serviceNotes.tips2')"></no-data-view-new>
      </template>
    </template>
  </div>
</template>

<script>
/* util */
import * as FormUtil from '@src/component/form/util';
import { formatDate, cutAtTextContent } from 'pub-bbx-utils';
import _ from 'lodash';
import * as IMApi from '@src/api/ImApi.js';
import * as TaskApi from '@src/api/TaskApi.ts';
import EventEditForm from '@src/modules/event/components/EventEditForm/EventEditForm.vue';
import FormSelect from '@src/component/form/components/FormSelect/FormSelect1.vue';
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import {enCodeAtText, atTextToUsers} from '@src/util/atText'
import { useTenantId, useRootUser } from '@hooks/useRootWindow.ts';
import { productSelectConversion } from '@src/util/conversionFunctionUtil.ts';
import { openTabForProductView } from '@src/util/business/openTab'
/* constant */
import { REQUIRES_PRODUCT_MESSAGE } from '@src/model/const/Alert.ts'
import { sessionStorageGet, sessionStorageSet, sessionStorageRemove } from '@src/util/storageV2'

import NoDataViewNew from '@src/component/common/NoDataViewNew';
const formValueStorageKey = 'im_remarkstorage_beforehandup'
const SystemKeys = [
  'id',
  'bizId',
  'bizType',
  'serviceNumber',
  'consultName',
  'solveStatus',
  'serviceRemark',
  'remarkProduct',
];
export default {
  name: 'service-notes',
  props: {
    isConversation: { type: Boolean, default: false },
    conversationStatus:  [Number, String],
    id: [Number, String],
    bizType: { type: [Number, String], default: 1 },
    customerId: {
      type: String,
      default: ''
    },
    ImSettingConfig: {
      type: Object,
      default: () => {
        return {
          serviceRemarkRequired: null,
        };
      },
    },
    bizNo:{ type:  String, default: ''},
    module:{
      type:  String, default: '会话详情'
    },
    phone:{
      type:  String, default: ''
    },  
    isShowOperateRow: {
      type: Boolean,
      default: true,
    }
  },
  inject:['initData'],
  data() {
    return {
      visible: false,
      formBackup: {},
      columnNum: 1,
      selfFields: [],
      // 初始化数据
      Info: {},
      Amendment: false,
      // 编辑保存用数据
      formData: {},
      formStatus: '',
      isInfo: false,
      // 初始化字段与参数
      InitData: [
        {
          key: 'attribute',
          value: {},
        },
        {
          key: 'solveStatus',
          value: '',
        },
        {
          key: 'serviceRemark',
          value: '',
        },
      ],
      Time: 0,
      loading:false,
      atUsers:[],
      loadPage:true,
      validation: this.buildValidation(),
      needServerDeleFiles: [],
    };
  },
  computed: {
    fields() {
      let originFields = this.selfFields || [];
      let sortedFields = originFields
        .sort((a, b) => a.orderId - b.orderId)
        .map(f => {
          if (f.fieldName === 'serviceNumber' && f.isSystem) {
            f.isNull = 1;
          }
          return f;
        });
      return FormUtil.migration(sortedFields);
    },
    fieldsInfo() {
      const info = [
        {
          displayName: this.$t('common.fields.createTime.displayName'),
          fieldName: 'createTime',
        },
        {
          displayName: this.$t('common.fields.createCustomerServiceName.displayName'),
          fieldName: 'customerServiceName',
        },
        {
          displayName: this.$t('common.fields.relationUserId.displayName'),
          fieldName: 'createUserName',
        },
      ];
      if (this.fields.length) {
        return [...this.fields, ...info];
      }
      return [];
    },
    RequiredNotes() {
      // 无数据且必填，返回true
      return !this.isInfo && this.ImSettingConfig.serviceRemarkRequired === 1;
    },
    isEditForm(){
      return Object.keys(this.Info).length || this.Amendment
    },
    // 是否创建
    isAdd() {
      return !Object.keys(this.Info).length
    },
    formEditingMode() {
      return this.isAdd ? 'create' : 'edit'
    }
  },
  async mounted() {
    // await this.GetTemplateByTenantId();
    // this.loadPage = false
  },
  methods: {
    SaveEnd() {
      this.$track.clickStat(this.$track.formatParams('SAVE_AND_FINISH_SERVICE_NOTES'));

      this.$confirm(this.$t('im.detail.tips6'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          this.Save(true);
        })
        .catch(() => {});
    },
    Edit(Amendment) {
      this.Amendment = Amendment;
      this.getFormValueByStorage()
      if(this.Info.serviceRemark){
        this.atUsers = atTextToUsers(this.Info.serviceRemark).users || []
        this.formData.serviceRemark = atTextToUsers(this.Info.serviceRemark).content || '';
      }
      const isAdd = !Object.keys(this.Info).length
      Amendment && isAdd && this.$track.clickStat(this.$track.formatParams('ADD_SERVICE_NOTES'));
    },
    Save(Close = false) {
      if(!Close) this.$track.clickStat(this.$track.formatParams('SAVE_SERVICE_NOTES'));

      this.$refs.form.validate().then(vali => {
        if (!vali) return;
        let form = _.cloneDeep(this.formData)
        if (form.remarkProduct && form.remarkProduct.length) {
          form.remarkProduct = form.remarkProduct.map(item => {
            return {
              id: item.id,
              name: item.name,
              serialNumber: item.serialNumber
            }
          })
        }
        form.serviceRemark = enCodeAtText(form.serviceRemark, this.atUsers);
        let receivers = []
        this.atUsers.forEach(item=>{
          if(this.formData.serviceRemark.indexOf(`${item.displayName} `) > -1){
            receivers.push(item.userId)
          }
        })
        form.receivers = receivers.join(',')    
        let query = ''
        if(this.atUsers.length > 0){
          let queryData = {
            receivers:form.receivers,
            tenantId: useTenantId().value,
            content: cutAtTextContent(this.formData.serviceRemark),
            sendUserName: useRootUser()?.value.displayName,
            bizId: this.id,
            bizNo: this.bizNo,
            md: this.module
          };
          if(this.module == '呼叫中心'){
            queryData.phone = this.phone
          }
          query = '?';
          for (let i in queryData) {
            query += `&${i}=${queryData[i]}`;
          }
        }
        // 新增时服务备注详情为null
        if (Object.keys(this.Info).length) {
          if(this.formEditingMode == 'edit' && this.needServerDeleFiles.length) {
            // 传给后端的字段需要和后端定好 TODO: 王也 修改删除表示字段
            form['deleteFiles'] = this.needServerDeleFiles
          }
          // 编辑
          this.loading = true
          IMApi.UpdateInfo(form, query).then(async res => {
            if (res.code === 0) {
              await this.GetTemplateByTenantId();
              this.getInfoByBizId();
              this.removeFormValueByStorage();
              this.Amendment = false;
              if (Close) {
                this.Close();
              }
            } else {
              this.$message.error(res.message);
            }
          }).finally(()=>{
            this.loading = false
          })
        } else {
          // 新增
          this.loading = true
          IMApi.SaveInfo(form, query).then(async res => {
            if (res.code === 0) {
              await this.GetTemplateByTenantId();
              this.getInfoByBizId();
              this.removeFormValueByStorage();
              this.Amendment = false;
              if (Close) {
                this.Close();
              }
            } else {
              this.$message.error(res.message);
            }
          }).finally(()=>{
            this.loading = false
          })
        }
      });
    },
    Close() {
      if (!this.id) return;
      IMApi.finished({
        conversationId: this.id,
      }).then(res => {
        if (res.code === 0) {
          this.$message({
            message: this.$t('im.detail.btn3'),
            type: 'success',
          });
          this.$emit('refresh');
        } else {
          this.$message.error(res.message);
        }
      });
    },
    update({ field, newValue }) {
      if (SystemKeys.includes(field.fieldName)) {
        // 系统字段
        this.$set(this,'formData', {...this.formData, [field.fieldName]:newValue})
        // this.formData[field.fieldName] =  newValue;
      } else {
        // 自定义字段
        // this.formData[field.fieldName] = newValue;
        this.$set(this,'formData', {...this.formData, [field.fieldName]:newValue, attribute:{
          ...this.formData.attribute, [field.fieldName]:newValue
        }})
        // this.formData.attribute[field.fieldName] = newValue;
      }
    },
    getInfoByBizId() {
      IMApi.getInfoByBizId({
        bizId: this.id,
        bizType: this.bizType,
      }).then(async res => {
        if (res.code === 0) {
          this.isInfo = !!res.data;
          
          this.$emit('RequiredNotes', this.RequiredNotes);
          // 编辑
          this.Time = Date.now();

          if (!res?.data?.attribute) {
            const attributeValue = FormUtil.initialize(this.fields.filter(f=> !SystemKeys.includes(f.fieldName)), {});
            this.formData = { ...res.data, ...attributeValue };
            // attribute存的自定义字段的值，初始化也得给它赋默认值
            this.formData.attribute = attributeValue;
          } else {
            // 处理富文本
            if(this.selfFields.length) {
              res.data = await FormUtil.initRichTextContent(this.selfFields, res.data, false)
            }
            this.formData = { ...res.data, ...res.data.attribute };
          }
          // 产品数据处理
          if (this.formData.remarkProduct && this.formData.remarkProduct.length) {
            this.formData.remarkProduct = this.formData.remarkProduct.map(item => {
              item.value = item.id
              item.label = item.name
              return item
            })
          }
          this.formData.bizId = Number(this.id);
          this.formData.bizType = this.bizType;
          this.InitData.map(item => {
            if (!this.formData[item.key]) this.formData[item.key] = item.value;
          });

          // 咨询分类后端按照字符串存储，拆封成数据
          if (typeof this.formData.consultName === 'string')
            this.formData.consultName = this.formData.consultName.split('/');

          if(!res.data){
            // 未保存数据之前都使用缓存数据
            this.getFormValueByStorage()
          }else{
            this.removeFormValueByStorage()
          }
            
          // 处理展示数据
          if (res.data) {
            this.formStatus = 'edit';
            this.Info = { ...res.data, ...res.data.attribute };
            this.Info.createTime = formatDate(this.Info.createTime);
            this.Info.solveStatus = this.Info.solveStatusDesc;
            // 适配老数据，
            this.Info.serviceRemark = this.Info.serviceRemark.replaceAll(
              '\n',
              '<br />'
            );
          } else {
            this.Info = {};
          }
        }
      }).finally(() => {
        this.loadPage = false
      });
    },
    GetTemplateByTenantId() {
      return IMApi.getTemplateByTenantId().then(res => {
        if (res.code === 0) {
          this.selfFields = res.data;
        }
      });
    },
    head(src) {
      if (!src) return defaultAvatar
      return src
    },
    inputContent(event){
      let value = event.target.value;
      this.formData.serviceRemark = value;
    },
    /**
     * @description 搜索产品
     */
    async searchProduct(params = {}) {
      try {
        if (!this.customerId) return
        params.customerId = this.customerId
        let result = await TaskApi.getTaskCustomerProduct(params);

        if (!result.result || !result.result?.list) return;

        result.result.list = result.result.list.map((product) =>
          productSelectConversion(product)
        );
        
        return result.result;
      } catch (error) {
        console.warn('searchProduct -> error', error);
      }
    },
    openProductView(productId) {
      openTabForProductView(productId)
    },
    buildValidation(){
      return Object.freeze({
        product(value, field, changeStatus){
          changeStatus(true);
          let isProductRequired = field.isNull === 0;
          let isSelectedProduct = Array.isArray(value) && value.length > 0;
          return new Promise((resolve, reject) => {
            changeStatus(false);
            let errorMessage = isSelectedProduct ? '' : REQUIRES_PRODUCT_MESSAGE;
            resolve(isProductRequired ? errorMessage : '')
          })
        },
      });
    },
    /**
     * @des 在挂断前保存表单数据
     */
    saveFormValueBeforeHandUp(){
      if(!this.isEditForm) return
      sessionStorageSet(`${formValueStorageKey}_${this.id}`, JSON.stringify(this.formData))
    },
    /**
     * @des 获取上次服务备注缓存
     */
    getFormValueByStorage(){
      let storage_ = sessionStorageGet(`${formValueStorageKey}_${this.id}`)
      if(storage_){
        this.formData = JSON.parse(storage_)
      }
    },
    /**
     * @des 清除上次服务备注缓存
     */
    removeFormValueByStorage(){
      let storage_ = sessionStorageGet(`${formValueStorageKey}_${this.id}`)
      if(storage_){
        sessionStorageRemove(`${formValueStorageKey}_${this.id}`)
      }
    },
    getDeleteFiles(files) {
      this.needServerDeleFiles = [...this.needServerDeleFiles, ...files]
    },
  },
  watch: {
    id: {
      handler(newValue) {
        if(newValue) {
          this.GetTemplateByTenantId().then(()=>{
            this.getInfoByBizId()
          })

        }
      },
      immediate: true,
    },
  },
  components: {
    EventEditForm,
    FormSelect,
    NoDataViewNew,
  },
};
</script>
<style lang="scss">
.ServiceNotes{
  .form-item__text {
  padding: 0;
}
.form-item-attachment .form-item-control {
  overflow: inherit;
}
.advanced-search .form-item {
  width: 100%;
}
.advanced-search {
  padding: 0 !important;
}
.form-view-row .form-view-row-content {
  text-align: left;
}
.form-view-row {
  padding: 8px 12px;
}
.form-view-row label {
  text-align: left;
  margin-right: 12px;
}
.form-view-row .form-view-row-content {
  text-align: left;
}
.form-item {
  flex-wrap: wrap;
  display: flex;
  flex-direction: column;
}
.form-item label {
  width: 100%;
}
.fwbz_edit {
  .form-item {
    flex-wrap: wrap;
    display: flex;
    flex-direction: column;
  }
  .form-item-control {
    width: 100% !important;
  }
}
}
</style>
<style lang="scss" scoped>
::v-deep .el-button--danger:hover {
  background: #ff7875;
  border-color: #ff7875;
  color: #ffffff;
}
::v-deep .el-button--danger:focus {
  background: #ff7875;
  border-color: #ff7875;
  color: #ffffff;
}
.form-separator {
  margin: 0;
  padding: 0;
}
::v-deep .advanced-search {
  padding: 0 !important;
}
::v-deep .advanced-search .form-item label {
  text-align: left;
  padding: 0;
}
::v-deep .form-item-control .err-msg-wrap {
  min-height: 12px;
  padding-bottom: 0;
}
::v-deep .form_serviceNumber {
  text-align: left;
}
.form-view {
  background: none;
}
.form-builder {
  width: auto;
  padding: 0;
  background: none;
  overflow-y: auto;
}
.FormText {
  overflow: auto;
  justify-content: space-between;
  overflow-y: auto;
  .form-item {
    width: auto !important;
    .form_serviceNumber {
      display: block;
      width: 110px;
      padding: 4px 0 0 10px;
      line-height: 24px;
      margin: 0;
      flex-shrink: 0;
      word-break: break-all;
      height: 46px;
      padding-left: 0;
    }
    .form-item-control {
      text-align: left;
      // width: calc(100% - 110px);
      width: 100%;
    }
  }
}
.title {
  margin-top: 0.5rem;
  text-align: right;
  position: absolute;
  width: 100%;
  bottom: 0;
  padding: 10px 5px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #e8e8e8;
}
.advanced-search {
  overflow: auto;

  height: calc(100% - 70px);
  justify-content: space-between;
  // padding: 0;
  padding: 10px 15px 63px 15px;
  .two-columns {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      width: 50%;
    }
  }

  .form-item-container {
    justify-content: space-between;
  }

  .form-item {
    label {
      padding-left: 0;
    }

    width: 390px;
  }

  .advanced-search-btn-group {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    position: absolute;
    bottom: 0px;
    background: #fff;
    padding: 15px 20px;

    .base-button {
      margin: 0 10px;
    }
  }
}
.ServiceNotes {
  width: 100%;
  height: 100%;
  text-align: center;
  position: relative;
}
.default-img {
  text-align: center;
  padding-top: 48px;
  img {
    width: 160px;
    height: 160px;
  }
}
.default-msg {
  text-align: center;
  margin-top: 8px;
  color: $text-color-regular;
  font-size: $font-size-base;
  margin-bottom: 20px;
}
.form-item__text {
  text-align: left;
}
</style>
